<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
            <el-form-item label="企业" prop="enterpriseId">
                <el-select v-model="queryParams.enterpriseId">
                    <el-option v-for="item in options" :key="item.value" :value="item.value" :label="item.label">

                    </el-option>
                </el-select>

            </el-form-item>
            <el-form-item label="时间" prop="nickName">
                <el-date-picker v-model="dates" type="daterange" range-separator="至" start-placeholder="开始日期"
                    @change="changeDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd" end-placeholder="结束日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="测评" prop="appraisalId">
                <el-select v-model="queryParams.appraisalId">
                    <el-option v-for="item in appraisalList" :key="item.id" :value="item.id"
                        :label="item.appraisalName">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['enterpriseQR:enterpriseQR:add']">新增</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-table v-loading="loading" :data="configurationList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" align="center" width="55" type="index" />
            <el-table-column label="企业名称" align="center" prop="enterpriseName" min-width="200"
                :show-overflow-tooltip="true" />
            <el-table-column label="测评名称" align="center" prop="appraisalName" min-width="200"
                :show-overflow-tooltip="true" />
            <el-table-column label="测评开始时间" align="center" prop="validityBeginDate" min-width="120"
                :show-overflow-tooltip="true" />
            <el-table-column label="测评结束时间" align="center" prop="validityFinishDate" min-width="120"
                :show-overflow-tooltip="true" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" @click="handleQr(scope.row)"
                        v-hasPermi="['enterpriseQR:enterpriseQR:qrCode']">企业二维码</el-button>
                    <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
                        v-hasPermi="['enterpriseQR:enterpriseQR:edit']">修改</el-button>
                    <el-button size="mini" type="text" @click="handleDelete(scope.row)"
                        v-hasPermi="['enterpriseQR:enterpriseQR:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />


        <!-- 添加或修改测评分类对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="企业" prop="enterpriseId">
                    <!-- <el-cascader style="width: 300px;" v-model="form.enterpriseId" :options="options"
                        @change="handleCascaderChange"></el-cascader> -->
                    <el-select v-model="form.enterpriseId" @change="handleCascaderChange">
                        <el-option v-for="item in options" :key="item.value" :value="item.value" :label="item.label">

                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="测评" prop="appraisalId">
                    <el-select @change="selectappraisal" style="width: 300px;" v-model="form.appraisalId">
                        <el-option v-for="item in appraisalList" :key="item.id" :value="item.id"
                            :label="item.appraisalName">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="测评开始时间" prop="validityBeginDate">
                    <el-date-picker style="width: 300px;" v-model="form.validityBeginDate" type="date"
                        :picker-options="startPickerOptions" @change="handleStartDateChange" placeholder="选择日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="测评结束时间" prop="validityFinishDate">
                    <el-date-picker style="width: 300px;" v-model="form.validityFinishDate" type="date"
                        :picker-options="endPickerOptions" @change="handleEndDateChange" placeholder="选择日期">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>


        <el-dialog title="企业二维码" :visible.sync="openqrCodeUrl" width="700px" append-to-body>
            <!-- <el-form ref="formqrCode" :model="formqrCode" label-width="80px">
                <el-form-item label="厂区" prop="factoryId">
                    <el-select v-model="formqrCode.factoryId" @change="getenterpriseDeptData">
                        <el-option v-for="item in factoryData" :key="item.id" :value="item.id"
                            :label="item.enterpriseName">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="部门" prop="enterpriseDeptId">
                    <el-select v-model="formqrCode.enterpriseDeptId">
                        <el-option v-for="item in enterpriseDeptData" :key="item.id" :value="item.id"
                            :label="item.enterpriseName">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form> -->

            <el-card class="box-card">
                <div slot="header" class="clearfix">
                    <!-- <el-button type="primary" size="mini" @click="createQRCode">生成二维码</el-button> -->
                    <el-button type="primary" size="mini" @click="downloadQRCode"
                        v-hasPermi="['enterpriseQR:enterpriseQR:downLoad']">下载二维码</el-button>
                </div>
                <div ref="exportContainer" class="export-content">
                    <div>
                        <!-- <div ref="qrcode"></div> -->
                        <!-- <div ref="qrcodeContainer" style="margin-top:20px;"></div> -->
                        <img :src="qrCodeUrl" class="content-image" />
                    </div>
                </div>
            </el-card>
        </el-dialog>
    </div>
</template>

<script>
// import QRCode from 'qrcode'
import QRCode from 'qrcodejs2'
import { listQrCode, getQrCode, addQrCode, updateQrCode, delQrCode, getQrCodeImg } from '@/api/qrCode/qrCode.js'
import { enterpriseList } from "@/api/evaluation/appraisalTopic";
import { enterpriseUser } from '@/api/evaluationReport/index.js'
export default {
    name: "enterpriseQR",
    data() {
        return {
            formqrCode: {
                enterpriseDeptId: '',
                factoryId: ''
            },
            openqrCodeUrl: false,
            qrCodeUrl: '',
            // 表单校验
            rules: {
                validityFinishDate: [
                    { required: true, message: "测评结束时间不能为空", trigger: "blur" }
                ],
                validityBeginDate: [
                    { required: true, message: "测评开始时间不能为空", trigger: "blur" },
                    { validator: this.validateEndDate, trigger: 'change' }
                ],
                enterpriseId: [
                    { required: true, message: "企业不能为空", trigger: "blur" }
                ],
                appraisalId: [
                    { required: true, message: "测评不能为空", trigger: "blur" }
                ],
            },
            startPickerOptions: {
                disabledDate: (time) => {
                    if (this.form.validityFinishDate) {
                        return time.getTime() > new Date(this.form.validityFinishDate).getTime();
                    }
                    return false;
                }
            },
            endPickerOptions: {
                disabledDate: (time) => {
                    if (this.form.validityBeginDate) {
                        return time.getTime() < new Date(this.form.validityBeginDate).getTime();
                    }
                    return false;
                }
            },
            form: {},
            appraisalAbnormalStatusList: [
                {
                    id: '0',
                    name: '正常'
                },
                {
                    id: '1',
                    name: '异常'
                }
            ],
            appraisalList: [],
            dates: [],
            options: [],
            copyenterpriseUserList: [],
            value: [],
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 配置维护表格数据
            configurationList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                nickName: undefined,
                appraisalId: undefined,
                enterpriseDeptId: undefined,
                enterpriseId: undefined,
                factoryId: undefined,
                enterpriseName: undefined, factoryName: undefined, enterpriseDeptName: undefined,
                pageNum: 1,
                pageSize: 10,
                params: {
                    endTime: undefined,
                    beginTime: undefined,
                }
            },
            factoryData: [],
            enterpriseDeptData: [],
            enterpriseAllData: [],
            jumpRow: {},

            secretKey: '654c07d50d34ff7caa7bceabfab27404',

            appid: 'wx9fa3ff35c3e90ff3',
            path: 'pages/index',
            params: { id: '123', name: 'test' }
        };
    },
    created() {
        this.getList();
        enterpriseList().then(res => {
            this.appraisalList = res.rows
        })
        enterpriseUser().then(res => {
            this.enterpriseAllData = res.rows
            let newRows = res.rows.filter(item => item.parentId == 0)
            newRows.forEach(element => {
                element.value = element.id
                element.label = element.enterpriseName
            });
            this.options = newRows
        })
    },
    methods: {
        handleStartDateChange(val) {
            if (this.form.validityFinishDate && new Date(val) > new Date(this.form.validityFinishDate)) {
                this.$message.warning('开始时间不能大于结束时间');
                this.form.validityFinishDate = '';
            }
        },
        handleEndDateChange(val) {
            if (this.form.validityBeginDate && new Date(val) < new Date(this.form.validityBeginDate)) {
                this.$message.warning('结束时间不能小于开始时间');
                this.form.validityFinishDate = '';
            }
        },
        validateEndDate(rule, value, callback) {
            if (!value) {
                callback(new Error('请选择结束日期'));
            } else if (this.form.validityBeginDate && new Date(value) < new Date(this.form.validityBeginDate)) {
                callback(new Error('结束时间不能小于开始时间'));
            } else {
                callback();
            }
        },
        downloadQRCode() {
            const link = document.createElement('a')
            link.href = this.qrCodeUrl
            link.download = '企业二维码.png'
            link.click()
        },
        getenterpriseDeptData(e) {
            this.formqrCode.enterpriseDeptId = undefined
            this.enterpriseDeptData = this.enterpriseAllData.filter(item => item.parentId == e)
        },
        async createQRCode() {
            const response = await getQrCodeImg(this.jumpRow.id);
            const base64Data = await this.convertBlobToBase64(response);
            this.qrCodeUrl = base64Data;
        },
        convertBlobToBase64(blob) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();

                reader.onloadend = () => {
                    resolve(reader.result);
                };

                reader.onerror = (error) => {
                    reject(new Error(`文件读取失败: ${error.target.error}`));
                };

                // 开始读取Blob数据
                reader.readAsDataURL(blob);
            });
        },
        // 表单重置
        resetQrCode() {
            this.formqrCode = {
                enterpriseDeptId: null,
                factoryId: null
            };
            this.qrCodeUrl = null
            this.resetForm("formqrCode");
        },
        handleQr(row) {
            this.resetQrCode()
            this.jumpRow = row
            // this.factoryData = this.enterpriseAllData.filter(item => item.parentId == row.enterpriseId)
            // this.enterpriseDeptData = []
            this.createQRCode()
            this.openqrCodeUrl = true
        },
        selectappraisal(e) {
            this.appraisalList.forEach(item => {
                if (e == item.id) {
                    this.form.appraisalName = item.appraisalName
                }
            })
        },
        changeDate(e) {
            this.queryParams.params.beginTime = e[0]
            this.queryParams.params.endTime = e[1]
        },
        handleCascaderChange(e) {
            this.options.forEach(item => {
                if (e == item.id) {
                    this.form.enterpriseName = item.enterpriseName
                }
            })
        },

        /**
         * 更新企业相关名称
         * @param {Array} value 选中的值数组
         */
        updateEnterpriseNames(value) {
            const enterpriseMap = new Map(
                this.copyenterpriseUserList.map(item => [item.id, item.enterpriseName])
            );

            this.form.enterpriseName = enterpriseMap.get(value[0]) || '';
        },
        formatData(data) {
            for (let i = 0; i < data.length; i++) {
                if (data[i].children && data[i].children.length === 0) {
                    data[i].children = undefined; // 关键步骤
                } else if (data[i].children) {
                    this.formatData(data[i].children); // 递归处理子级
                }
            }
            return data;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加订单";
        },

        //  /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids
            getQrCode(id).then(response => {
                this.form = response.data;
                this.open = true;
                this.title = "修改订单";
            });
        },

        // 企业报告导出时   
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id != null) {
                        updateQrCode(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addQrCode(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal.confirm('是否确认删除订单数据项？').then(function () {
                return delQrCode(ids);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                enterprisevalue: null,
                appraisalId: null,
                validityBeginDate: null,
                validityFinishDate: null,
                enterpriseName: null,
                factoryName: null,
                enterpriseDeptName: null,
                enterpriseId: null,
                factoryId: null, enterpriseDeptId: null,
            };
            this.resetForm("form");
        },

        /** 查询配置维护列表 */
        getList() {
            this.loading = true;
            listQrCode(this.queryParams).then(response => {
                this.configurationList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dates = []
            this.value = []
            this.queryParams.enterpriseName = null
            this.queryParams.factoryName = null
            this.queryParams.enterpriseDeptName = null
            this.queryParams.enterpriseId = null
            this.queryParams.factoryId = null
            this.queryParams.enterpriseDeptId = null
            this.queryParams.params.beginTime = null
            this.queryParams.params.endTime = null
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.userId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        }
    }
};
</script>
<style scoped lang="scss">
.export-content {
    width: 600px;
    display: flex;
    justify-content: space-around;
}
</style>
